﻿using System;
using System.Collections.Generic;
using System.Text;
using Log4Nez.Interfaces;
using System.Xml;
using Log4Nez.Enumerations;
using Log4Nez.Loggers;
using System.Configuration;
using Log4Nez.Resources;

namespace Log4Nez.Factories
{
    internal static class DatabaseLoggerFactory
    {
        public static ILogger CreateDatabaseLogger(XmlNode loggerNode, LoggerType logType)
        {
            ILogger logger = null;
            string stringClassType = loggerNode.SelectSingleNode("PropertiesMapping") != null ? loggerNode.SelectSingleNode("PropertiesMapping").Attributes["class"].Value : null;
            if (!string.IsNullOrEmpty(stringClassType))
            {
                //Type classType = Type.GetType(stringClassType);
                Dictionary<string, string> properties = new Dictionary<string, string>();
                XmlNodeList nodiProperty = loggerNode.SelectNodes("PropertiesMapping/add");
                foreach (XmlNode property in nodiProperty)
                {
                    properties.Add(property.Attributes["property"].Value, property.Attributes["column"].Value);
                }
                XmlAttribute tableName = loggerNode.Attributes["tableName"];
                if (tableName == null)
                    throw new ConfigurationErrorsException(string.Format(ExceptionMessages.XmlConfigAttributeRequired,"tableName"));
                
                XmlAttribute connectionString = loggerNode.Attributes["connectionString"];
                if (connectionString == null)
                    throw new ConfigurationErrorsException(string.Format(ExceptionMessages.XmlConfigAttributeRequired, "connectionString"));

                logger = new DataBaseLogger(properties, connectionString.Value, tableName.Value);
            }
            return logger;
        }

    }
}
